package com.geek.novel.activity.book

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.content.res.AppCompatResources
import com.geek.novel.R
import com.geek.novel.activity.base.TitleBarActivity
import com.geek.novel.adapter.TodayBookAdapter
import com.geek.novel.common.Constant
import com.geek.novel.entity.BookCrawler
import com.geek.novel.entity.BookRead
import com.geek.novel.network.ImageDownloader.Companion.getInstance
import com.geek.novel.network.RslHandler
import com.geek.novel.services.BookCrawlerRepository
import com.geek.novel.services.BookRepository
import com.geek.novel.services.NovelService
import com.geek.novel.utils.*
import com.geek.novel.view.list.AllListView
import com.geek.novel.view.loading.LoadingDialogUtil
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.geek.novel.vo.AuthorBooksVo
import com.geek.novel.vo.BookDetailVo
import kotlinx.android.synthetic.main.activity_book_detail.*
import kotlinx.android.synthetic.main.layout_book_detail_author_books.*
import kotlinx.android.synthetic.main.layout_book_detail_content.*
import kotlinx.android.synthetic.main.layout_book_detail_info.*
import kotlinx.android.synthetic.main.layout_book_detail_rate.*
import kotlinx.android.synthetic.main.layout_book_detail_toolbar.*


class BookDetailActivity: TitleBarActivity() , RslHandler {

	/**书籍详情*/
	private var bookDetail: BookRead? = null
	
	/**作者的书籍列表*/
	private var authorBookList = ArrayList<BookRead>()
	
	/**书籍的数据库操作接口*/
	private var bookRepository = BookRepository.getInstance()

	/**书籍的数据库操作接口*/
	private var bookCrawlerRepository = BookCrawlerRepository()

	/**是否收藏*/
	private var collect = false

	override fun pageName(): String{
		return ""
	}

	/**小说服务*/
	private lateinit var novelService: NovelService
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_book_detail)

		//初始化服务对象
		novelService = NovelService(this)

		try {
			//初始化控件
			this.initView()

			//获取书籍数据
			this.initBookData()

		}catch (e: Exception){
			ToastUtils.toast(e.message)
			finish()
		}
	}

	/**初始化控件*/
	private fun initView(){
		//初始化标题栏
		this.initTitleBar()

		//初始化下拉刷新功能
		this.initRefreshLayout()
		
		//初始化作者书籍列表
		this.initAuthorBookList()

		//添加点击事件，前往评价页面
		ly_book_detail_rate.setOnClickListener(this)
		
		//底部加书架按钮的点击事件
		ly_book_detail_add_book.setOnClickListener(this)
		//底部听书按钮的点击事件
		ly_book_detail_listen_book.setOnClickListener(this)
		//底部听书按钮的点击事件
		ly_book_detail_read_book.setOnClickListener(this)
		
	}

	/**显示收藏图标*/
	private fun initCollectIconBtn(){
		val user = SecurityUtil.getPrincipal()
		if(user == null){
			super.hideIconBtn()
		}else{
			if(this.collect){
				super.showIconBtn(R.drawable.icon_collected)
			}else{
				super.showIconBtn(R.drawable.icon_collect_default)
			}
		}
	}

	/**标题右侧图标按钮的点击事件*/
	override fun onIconBtnClick(view: View) {
		if(this.bookDetail == null){
			ToastUtils.toast("获取书籍信息不能为空！")
			return
		}
		//判断是否收藏并调用接口
		if(!this.collect){
			novelService.addUserCollect(this.bookDetail!!.bookId!!)
		}else{
			novelService.removeUserCollect(this.bookDetail!!.bookId!!)
		}

	}

	/**初始化标题栏*/
	private fun initTitleBar() {
		//标题栏透明
		super.setActionBarTransparent(Color.WHITE)
		//调整顶部标题栏的文本颜色
		super.setActionBarTitleAlpha(0F)
		
		//设置容器为填充高度状态
		super.setViewContainerFill(ly_book_detail_panel)
		//隐藏掉填充容器顶部的占位块
		super.hideContainerBlock()
	}

	/**
	 * 初始化下拉刷新功能
	 */
	private fun initRefreshLayout(){
		//滚动加载相关
		book_detail_refresh_layout.setRefreshHeader(book_detail_classics_header)
		book_detail_refresh_layout.setEnableLoadMore(false)//不开启滚动加载
		book_detail_refresh_layout.setOnRefreshListener {
			if(bookDetail == null || TextUtils.isEmpty(bookDetail!!.bookId)){
				ToastUtils.toast("请等待数据加载完毕！")
				return@setOnRefreshListener
			}
			val book = bookDetail!!
			//发起请求获取首页推荐小说
			this.getBookDetail(book.bookId!!)
		}
		//设置滚动监听
		book_detail_scroll_view.setOnScrollChangeListener { _, _, scrollY, _, _ ->
			//设置顶部标题栏的背景颜色
			this.offsetActionBarAlpha(scrollY)
			//设置顶部标题栏的文本颜色
			this.offsetActionBarTextAlpha(scrollY)
			//将图片挪上去
			this.offsetBookDetailPosition(scrollY)
		}
	}

	/**
	 * 设置顶部标题栏的背景颜色
	 */
	private fun offsetActionBarAlpha(scrollY: Int){
		//获取滚动可视区的高度
		val scrollPanelHeight = this.getScrollPanelHeight()
		//调整顶部标题栏的背景颜色
		super.setActionBarBackgroundAlpha(scrollY/(scrollPanelHeight))
	}

	/**
	 * 设置顶部标题栏的文本颜色
	 */
	private fun offsetActionBarTextAlpha(scrollY: Int){
		//获取滚动可视区的高度
		val scrollPanelHeight = this.getScrollPanelHeight()
		//微调，挪N个dip之后才显示标题，好看一点
		val offsetTop = CommUtil.dip2px(50F)
		//调整顶部标题栏的文本颜色
		super.setActionBarTitleAlpha((scrollY-offsetTop)/scrollPanelHeight)
	}

	/**
	 * 获取滚动可视区的高度
	 */
	private fun getScrollPanelHeight(): Float{
		//获取顶部图片的高度
		val imageBoxHeight = resources.getDimension(R.dimen.book_detail_top_image_height)
		//计算高度还要减去标题栏的高度
		val actionBarHeight = super.getActionBarHeight()
		return imageBoxHeight-actionBarHeight
	}

	/**
	 * 移动书籍详情图片的位置
	 */
	private fun offsetBookDetailPosition(scrollY: Int){
		ly_book_detail_container.translationY = -scrollY.toFloat() /2
	}

	/**初始化书籍数据*/
	private fun initBookData() {
		val extras = intent.extras ?: throw Exception("入参对象不能为空！必须带书籍id才能访问该页面!")
		val bookId = extras.getString("bookId")
		if(TextUtils.isEmpty(bookId)){
			throw Exception("必须带书籍id才能访问该页面！")
		}
		this.getBookDetail(bookId!!, true)

		//添加点击数
		novelService.addVisitCount(bookId)
	}

	/**发起请求获取数据详情*/
	private fun getBookDetail(bookId: String, showLoading: Boolean=false){
		//显示loading
		if(showLoading){
			LoadingDialogUtil.getInstance().showLoading("数据获取中...")
		}
		//发起请求获取数据
		novelService.getBookDetail(bookId)
	}

	/**数据加载完成，显示到页面上*/
	@SuppressLint("SetTextI18n")
	private fun initBookDetail(){
		if(bookDetail == null){
			ToastUtils.toast("请等待数据加载完毕！")
			return
		}

		val book = bookDetail!!

		//获取作者的书籍数据
		novelService.getAuthorBooks(book.authorId!!, book.bookId!!)

		//判断是否在书架中
		this.initBookshelf(book.bookId)

		val bookName = BookUtil.formatBookName(book.bookName)
		var bookDesc = BookUtil.formatBookDescBlank(book.bookDesc)
		if(FormatUtil.isEmpty(bookDesc)){
			bookDesc = "暂无简介"
		}

		//设置标题文本
		super.setTitle(bookName)

		//图片的宽高
		val width: Float = this.resources.getDimension(R.dimen.book_detail_image_width)
		val imgId = book.imgId
		iv_book_detail_image.setBookName(bookName)
		iv_book_detail_image.loadBookImage(imgId)

		//书籍简介
		tv_book_detail_desc.text = bookDesc

		//将小说封面作为背景图片并添加毛玻璃效果
		val bgImageHeight = width/3 *4
		loadBookImage(imgId, iv_book_detail_top_image, width, bgImageHeight)

		//书名、字体加粗
		tv_book_detail_book_name.text = bookName
		tv_book_detail_book_name.paint.isFakeBoldText = true

		//作者名
		val authorName = BookUtil.formatAuthorName(book.authorName)
		tv_book_detail_author_name.text = "$authorName >"

		//书籍其他信息：类型 · 连载 · 13万字
		val otherInfo = StringBuilder()
		if (!TextUtils.isEmpty(book.categoryStr)) {
			otherInfo.append(book.categoryStr)
		}else{
			otherInfo.append("暂无类型")
		}
		otherInfo.append("  ·  ")
		otherInfo.append(if (book.bookStatus == 0) "连载中" else "已完结")
		//字数
		val wordCount = book.wordCount
		if (wordCount > 0) {
			otherInfo.append(" · ")
			val wordCountStr = FormatUtil.formatNumberCount(wordCount, 1)
			otherInfo.append(wordCountStr).append("字")
		}

		tv_book_detail_other_info.text = otherInfo.toString()

		//设置书籍评分
		this.initBookRate()
	}

	/**更新本地数据*/
	private fun updateLocalBookData(){
		if(bookDetail == null){
			ToastUtils.toast("请等待数据加载完毕！")
			return
		}
		val book = bookDetail!!
		val localBook = bookRepository.findBookByBookId(book.bookId) ?: return
		localBook.bookStatus = book.bookStatus
		localBook.endTime = book.endTime
		bookRepository.save(localBook)
	}
	
	/**
	 * 初始化作者书籍列表
	 */
	private fun initAuthorBookList(){
		lv_author_book_list.setAdapter(TodayBookAdapter(authorBookList))
		lv_author_book_list.setOnItemClickListener(object: AllListView.OnItemClickListener{
			override fun onItemClick(parent: ViewGroup?, view: View?, position: Int, id: Long) {
				//前往书籍详情页面
				gotoBookDetailPage(authorBookList[position])
			}
		})
	}
	
	/**
	 * 前往书籍详情页面
	 */
	private fun gotoBookDetailPage(book: BookRead){
		val params = Bundle()
		params.putString("bookId", book.bookId)
		startActivityByAnim(this, BookDetailActivity::class.java, params)
	}
	
	/**
	 * 初始化作者书籍列表
	 */
	private fun refreshAuthorBookList(list: List<BookRead>){
		authorBookList.clear()
		if(list.isEmpty()){
			tv_book_detail_no_author_books.visibility = View.VISIBLE
			lv_author_book_list.visibility = View.GONE
		}else{
			tv_book_detail_no_author_books.visibility = View.GONE
			lv_author_book_list.visibility = View.VISIBLE
			authorBookList.addAll(list)
			lv_author_book_list.getAdapter()!!.notifyDataSetChanged()
		}
	}

	/**设置书籍评分*/
	@SuppressLint("SetTextI18n")
	private fun initBookRate(){
		if(this.bookDetail == null){
			return
		}
		val rateCount = FormatUtil.isNullToLongZero(this.bookDetail!!.rateCount)
		val rate = FormatUtil.isNullToString(this.bookDetail!!.rate, "0.0")

		//设置评分内容和星星
		tv_book_detail_rate.text = rate
		rs_book_detail_star_rate.setStarMark(rate!!.toFloat())

		//设置评分的人数
		var realCountStr = "暂无评价"
		if(rateCount > 0L){
			realCountStr = FormatUtil.formatNumberCount(rateCount, 1) + "人评价"
		}
		tv_book_detail_rate_count.text = realCountStr

		//阅读数
		val readCount = FormatUtil.isNullToLongZero(this.bookDetail!!.readCount)
		val readCountStr = if(readCount>0L){ FormatUtil.formatNumberCount(readCount, 1) + "人" }else{ "0" }
		tv_book_detail_collect.text = readCountStr

		//点击数
		val visitCount = FormatUtil.isNullToLongZero(this.bookDetail!!.visitCount)
		val visitCountStr = if(visitCount>0L){ FormatUtil.formatNumberCount(visitCount, 1) }else{ "0" }
		tv_book_detail_collect_total.text = visitCountStr
	}

	private fun loadBookImage(imgId: String?, iv: ImageView, width: Float, height: Float) {
		val errorImg = R.drawable.book_image_loading
		if (TextUtils.isEmpty(imgId)) {
			iv.setImageDrawable(getDrawable(errorImg))
		} else {
			val imageUrl = Constant.HTTP_IMAGE_URL + imgId
			//加载图片
			val downloader = getInstance(this)
			downloader.build(imageUrl)
				.resize(width, height)
				.placeholder(errorImg)
				.error(errorImg)
				.centerCrop()
				.stackBlur(this, 10)
				.into(iv)
		}
	}
	
	/**初始化书架*/
	private fun initBookshelf(bookId: String?){
		val book = bookRepository.findBookByBookId(bookId)
		if(book != null){
			val drawable: Drawable?
			val text: String
			val textColor: Int
			if(book.collect){
				drawable = AppCompatResources.getDrawable(this, R.drawable.icon_book_collected)
				text = resources.getString(R.string.book_detail_in_collect)
				textColor = resources.getColor(R.color.color_primary, null)
			}else{
				drawable = AppCompatResources.getDrawable(this, R.drawable.icon_book_collect)
				text = resources.getString(R.string.book_detail_add_collect)
				textColor = resources.getColor(R.color.c333, null)
			}
			ly_book_detail_add_book_text.text = text
			ly_book_detail_add_book_text.setTextColor(textColor)
			ly_book_detail_add_book_icon.setImageDrawable(drawable)
		}
	}
	/**加入书架功能*/
	private fun addBookshelf(){
		if(this.bookDetail == null){
			ToastUtils.toast("数据未加载完成，请稍候")
			return
		}
		val book = this.bookDetail!!
		//保存书架，并挪到最顶部
		bookRepository.toggleBookshelf(book)

		//修改书籍阅读数
		if(book.collect){
			novelService.addReadCount(book.bookId!!)
		}else{
			novelService.minusReadCount(book.bookId!!)
		}
		this.initBookshelf(book.bookId)
	}


	/**保存书籍爬虫源信息*/
	private fun handleInitBookCrawler(list: List<BookCrawler>?){
		if(list == null){
			ToastUtils.toast("获取到数据源为空！将无法进入阅读页面")
			return
		}
		//保存数据源
		bookCrawlerRepository.saveAll(list)
	}

	override fun clickEvent(id: Int, v: View) {
		when(id){
			//前往书籍评价页面
			R.id.ly_book_detail_rate -> {
				//TODO 前往书籍评价页面
				ToastUtils.toast("评价功能正在开发中...")
			}
			//加入书架
			R.id.ly_book_detail_add_book -> {
				this.addBookshelf()
			}
			//前往听书页面
			R.id.ly_book_detail_listen_book -> {
				//TODO 前往听书页面
				ToastUtils.toast("听书功能正在开发中...")
			}
			//前往阅读页面
			R.id.ly_book_detail_read_book -> {
				val book = bookDetail!!
				val bookDb = bookRepository.findBookByBookId(book.bookId)
				if(bookDb == null){
					bookRepository.save(book)
				}else{
					if(bookDb.collect){//已经在书架，保持置顶
						bookRepository.saveBookToTop(bookDb)
					}
				}
				//跳转到阅读页面
				val params = Bundle()
				params.putString("bookId", book.bookId)
				startActivityForResultByAnim(this, ViewerActivity::class.java, params, Constant.ACTIVITY_RESULT_VIEWER)
			}
		}
	}

	/**页面回显*/
	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		super.onActivityResult(requestCode, resultCode, data)
		when(requestCode){
			//阅读页面的回显
			Constant.ACTIVITY_RESULT_VIEWER->{
				if(bookDetail == null){
					ToastUtils.toast("数据加载出错！请重试或者联系客服")
					return
				}
				//判断是否在书架中
				this.initBookshelf(bookDetail!!.bookId)
			}
		}
	}

	override fun onError(code: Int, err: ApiErrorResult) {
		when(code){
			//获取书籍详情
			Constant.HTTP_KEY_APP_GET_BOOK_DETAIL->{
				//下拉加载
				book_detail_refresh_layout.finishRefresh(false)
			}
		}
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//获取书籍详情
			Constant.HTTP_KEY_APP_GET_BOOK_DETAIL->{
				//下拉加载
				book_detail_refresh_layout.finishRefresh(true)
				//loading弹框
				LoadingDialogUtil.getInstance().dismiss()
				//获取数据信息
				val bookDetailVo = result.getData() as BookDetailVo
				bookDetail = bookDetailVo.bookDetail
				if(bookDetail == null){
					ToastUtils.toast("数据加载出错！请重试或者联系客服")
					return
				}
				//保存爬虫源信息
				this.handleInitBookCrawler(bookDetailVo.bookCrawlerList)

				//加载数据
				this.initBookDetail()

				//更新本地数据
				this.updateLocalBookData()

				//显示收藏图标
				this.collect = bookDetailVo.collect
				this.initCollectIconBtn()
				super.setIconBtnPadding(CommUtil.dip2px(8F).toInt())
			}
			//根据作者id获取作者的所有书籍
			Constant.HTTP_KEY_APP_GET_AUTHOR_BOOKS->{
				val authorBooksVo = result.getData() as AuthorBooksVo
				val bookList = authorBooksVo.bookList
				if(bookList == null){
					ToastUtils.toast("数据加载出错！请重试或者联系客服")
					return
				}
				//加载数据
				this.refreshAuthorBookList(bookList)
			}
			//用户加收藏
			Constant.HTTP_KEY_APP_USER_COLLECT_ADD -> {
				this.collect = true
				this.initCollectIconBtn()
				ToastUtils.toast("添加收藏成功")
			}
			//用户取消收藏
			Constant.HTTP_KEY_APP_USER_COLLECT_REMOVE -> {
				this.collect = false
				this.initCollectIconBtn()
				ToastUtils.toast("取消收藏成功")
			}
		}
	}

}